package com.hand.wfive.base

import android.content.Context
import android.content.res.Resources
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import com.hand.wfive.R
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog

abstract class BaseBottomSheetDialog(context: Context) : BottomSheetDialog(context, R.style.Theme_BottomSheetDialog_Base) {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getContentViewId())
        initView()
    }

    override fun onStart() {
        super.onStart()
        changePeekHeight()
        val window = window
        if (window != null) {
            window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, getPeekHeight())
            window.setGravity(Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL)

            //按空白处不能取消动画
//            window.getAttributes().width = QMUIDisplayHelper.getScreenWidth(getContext());
            setCanceledOnTouchOutside(isCancelable())
            setCancelable(isCancelable())
        }
    }

    private fun changePeekHeight() {
        val peekHeight = getPeekHeight()
        if (peekHeight > 0) {
            val bottomSheet = findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
            if (bottomSheet != null) {
                val behavior = BottomSheetBehavior.from(bottomSheet)
                // 设置是否可拖拽
                behavior.isDraggable = isDraggable()
                behavior.peekHeight = peekHeight
                // 解决平板上宽度无法填满问题
                behavior.maxWidth = Resources.getSystem().displayMetrics.widthPixels
                val layoutParams = bottomSheet!!.layoutParams
                if (isFixHeight()) {
                    layoutParams.height = peekHeight
                }
                bottomSheet.layoutParams = layoutParams
            }
        }
    }
    protected open fun isCancelable(): Boolean {
        return false
    }

    protected open fun isDraggable(): Boolean {
        return false
    }

    protected open fun isFixHeight(): Boolean {
        return true
    }

    protected open fun getPeekHeight(): Int {
        return WindowManager.LayoutParams.MATCH_PARENT
    }

    protected abstract fun getContentViewId(): Int
    protected abstract fun initView()

}